package de.dhbw.karlsruhe.picsim.rs232;

import app.Com;
import app.Parameters;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 2, 2010
 * Time: 5:12:19 PM
 */
public class ComManagerImpl implements ComManager {
    private static final Log log = LogFactory.getLog(ComManagerImpl.class);
    private final Collection<Listener> listeners = new CopyOnWriteArrayList<Listener>();
    @Nullable
    private ComHandler currentCom = null;
    @Nullable
    private
    String currentPort = null;


    @Override
    @NotNull
    public List<? extends String> getAllAvailablePorts() {
        try {
            return new Com(new Parameters()).getFreeSerialPort();
        } catch (Exception e) {
            log.error(e);
        }
        return Collections.emptyList();

    }

    @Override
    public void closeActivePort() {
        if (currentCom != null) {
            currentCom.dispose();
        }
        currentCom = null;
        currentPort = null;

    }

    @Override
    @Nullable
    public String getCurrentPort() {
        return currentPort;
    }

    @Override
    public boolean changeComPort(@NonNls final String toPort) {
        try {
            if (currentCom != null) {
                currentCom.dispose();
            }
            final ComHandler newPort = new ComHandlerImpl(toPort);
            for (final Listener listener : listeners) {
                newPort.addListener(listener);
            }
            currentCom = newPort;
            currentPort = toPort;
            return true;
        } catch (Exception e) {
            log.error(e);
            return false;
        }
    }

    @Override
    public void dispose() {
        closeActivePort();
        listeners.clear();

    }

    @Override
    public boolean isReady() {
        return currentCom != null && currentCom.isReady();
    }

    @Override
    public void sendString(@NotNull String message) {
        if (currentCom != null) {
            currentCom.sendString(message);
        }

    }

    @Override
    public void addListener(@NotNull Listener listener) {
        listeners.add(listener);
        if (currentCom != null) {
            currentCom.addListener(listener);
        }

    }

    @Override
    public void removeListener(@NotNull Listener listener) {
        listeners.remove(listener);
        if (currentCom != null) {
            currentCom.removeListener(listener);
        }

    }
}
